package FrameWork.Audio;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;

/**
 *
 * @author Mikko
 */
public class SoundEffect {
    private final static String PATH = "/audio/";

    private final String file;
    private Player player = null;
    private VolumeControl volumeControl;

    public SoundEffect(String fileName) {
        file = PATH + fileName;
    }

    public void load() {
        if(player != null) return;
        try {
            InputStream is = this.getClass().getResourceAsStream(file);
            player = Manager.createPlayer(is , "audio/x-wav");
            player.prefetch();
            volumeControl = (VolumeControl) player.getControl("VolumeControl");
        } catch (IOException e) {
        } catch (MediaException e) {
        }
    }
    
    public void close() {
        if(player == null) return;
        player.close();
        player = null;
        volumeControl = null;
    }

    public void play(int _volume) {
        
            try {
                player.prefetch();
                player.stop();
                player.setMediaTime(0);
                volumeControl.setLevel(_volume);
                player.start();
            } catch (MediaException ex) {
            }
        
    }
     public void playloop(int _volume) {
        
            try {
                player.prefetch();
                player.stop();
                player.setMediaTime(0);
                volumeControl.setLevel(_volume);
                player.setLoopCount(-1);
                player.start();
            } catch (MediaException ex) {
            }
        
    }
      public void PlayNoStop(int _volume) {
        
            try {
                player.prefetch();
                player.setMediaTime(0);
                volumeControl.setLevel(_volume);
                player.start();
            } catch (MediaException ex) {
            }
        
    }
     public void Stop (){
           try {
                player.stop();
            } catch (MediaException ex) {
            }
      }
    public void deallocate() {
        player.deallocate();
    }
}
